package com.song.elasticsearch.config;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.hwclient.HwRestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @Description: 初始化Elasticsearch客户端
 * @Author: clliu
 * @Date: 2022/04/13
 * @Version V1.0
 **/
@Slf4j
@Configuration
public class ElasticsearchConfig {
    @Value("${configPath}")
    private String config;


    public String configPath(){
        String configPath = "";
        try {
            configPath = ResourceUtils.getURL("classpath:").getPath();
            configPath = URLDecoder.decode(configPath, "UTF-8");
            if (System.getProperty("os.name").toLowerCase().contains("win")){
                configPath = configPath.substring(1).replace("/", "\\");
            }else{
                configPath = config;
            }
            log.info("es读取配置路径为：configPath=====>" + configPath);
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }
        return configPath;
    }

    @Bean
    public RestClient restClient() {
        HwRestClient hwRestClient = new HwRestClient(configPath());
        return hwRestClient.getRestClient();
    }

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        HwRestClient hwRestClient = new HwRestClient(configPath());
        return new RestHighLevelClient(hwRestClient.getRestClientBuilder());
    }


}
